import { query } from "../mysqlQuery.js";
import path, { resolve } from "path";
import fs from "fs";
import Joi from "joi";
import { StringDecoder } from "string_decoder";
import SDTime from "silly-datetime"; //时间格式化处理插件
const decoder = new StringDecoder("utf-8"); //解析器，将buffer以utf-8编码方式解析
//app
//阅读页面接口
//获取小说评论查询接口
export function app_getNovelComment(req, res, next) {
  query([
    {
      sql: "select * from app_comment where novel_id=? limit ?,?;",
      values: [
        req.query.novel_id,
        (Number(req.query.pageNum) - 1) * Number(req.query.pageSize),
        Number(req.query.pageSize),
      ],
    },
  ])
    .then(async (data) => {
      let i = 0;
      while (i < data[0].rows.length) {
        let out = await query([
          {
            sql: "select head_imgurl from users where user_id =?;",
            values: [data[0].rows[i].user_id],
          },
        ]);
        data[0].rows[i].head_img=out[0].rows[0].head_imgurl
        i++;
      }
      res.send({
        code: 200,
        msg: "成功",
        data: data[0].rows,
      });
    })
    .catch((err) => {
      next(err);
    });
}
//获取小说章节内容查询接口
export function app_getNovelChapterContent(req, res, next) {
  query([
    {
      sql: "select * from app_novel_chapter where chapter_id=?;",
      values: [req.query.chapter_id],
    },
  ])
    .then((data) => {
      res.send({
        code: 200,
        msg: "成功",
        data: data[0].rows,
      });
    })
    .catch((err) => {
      next(err);
    });
}
//获取小说目录接口
export function app_getNovelCatalogue(req, res, next) {
  query([
    {
      sql: "select id,title,chapter_id,create_time,status,update_time,word,sort from app_novel_chapter where novel_id=? order by sort asc;",
      values: [req.query.novel_id],
    },
  ])
    .then((data) => {
      res.send({
        code: 200,
        msg: "成功",
        data: data[0].rows,
      });
    })
    .catch((err) => {
      next(err);
    });
}
//搜索页面接口
export function app_getSearchhistory(req, res, next) {
  query([
    {
      sql: "select * from app_searchhistory",
      values: [],
    },
  ])
    .then((data) => {
      res.send({
        code: 200,
        msg: "成功",
        data: data[0].rows,
      });
    })
    .catch((err) => {
      next(err);
    });
}
//查询小说与分类小说接口
export function app_getSearchFindNovels(req, res, next) {
  let sql = "",
    values = [];
  if (req.query.novel_id != "") {
    sql = "select * from app_novel where novel_id=?";
    values = [req.query.novel_id];
  } else {
    sql = "select * from app_novel where category=? order by id asc limit ?, ?"; //注意limit 开始下标,截取下标开始后多少个，而不是结束下标，坑啊
    values = [
      req.query.category,
      (Number(req.query.pageNum) - 1) * Number(req.query.pageSize),
      Number(req.query.pageSize),
    ];
  }

  query([
    {
      sql,
      values,
    },
  ])
    .then((data) => {
      data[0].rows.forEach((item) => {
        item.pic = "data:image/jpg;base64," + item.pic.toString("base64");
        if (item.word >= 10000000) {
          item.word = Math.floor(Number(item.word) / 10000000) + "千万";
        } else if (item.word >= 10000) {
          item.word = Math.floor(Number(item.word) / 10000) + "万";
        } else if (item.word >= 1000) {
          item.word = Math.floor(Number(item.word) / 1000) + "千";
        } else {
        }
      });
      res.send({
        code: 200,
        msg: "成功",
        total: data[0].rows.length,
        data: data[0].rows,
      });
    })
    .catch((err) => {
      next(err);
    });
}
//搜索框模糊查询
export function app_getSearchNovelName(req, res, next) {
  console.log(req.query.content);
  query([
    {
      sql: `select * from app_novel where title like '%${req.query.content}%' order by id asc limit ?,?`,
      values: [
        (Number(req.query.pageNum) - 1) * Number(req.query.pageSize),
        Number(req.query.pageSize),
      ],
    },
  ])
    .then((data) => {
      data[0].rows.forEach((item) => {
        item.pic = "data:image/jpg;base64," + item.pic.toString("base64");
        if (item.word >= 10000000) {
          item.word = Math.floor(Number(item.word) / 10000000) + "千万";
        } else if (item.word >= 10000) {
          item.word = Math.floor(Number(item.word) / 10000) + "万";
        } else if (item.word >= 1000) {
          item.word = Math.floor(Number(item.word) / 1000) + "千";
        } else {
        }
      });
      res.send({
        code: 200,
        total: data[0].rows.length,
        msg: "成功",
        data: data[0].rows,
      });
    })
    .catch((err) => {
      next(err);
    });
}
//分类分类
export function app_getClassifys(req, res, next) {
  query([
    {
      sql: "select * from classifys where sex=?",
      values: [req.query.sex],
    },
  ])
    .then((data) => {
      res.send({
        code: 200,
        msg: "成功",
        data: data[0].rows,
      });
    })
    .catch((err) => {
      next(err);
    });
}

//首页书荒广场
export function app_getBookgardensquare(req, res, next) {
  query([
    {
      sql: "select * from app_bookgardensquare",
      values: [],
    },
  ])
    .then((data) => {
      res.send({
        code: 200,
        msg: "成功",
        data: data[0].rows,
      });
    })
    .catch((err) => {
      next(err);
    });
}

//首页推荐榜
export function app_getRecommandNovels(req, res, next) {
  query([
    {
      sql: "select * from app_recommend",
      values: [],
    },
  ])
    .then(async (data) => {
      let i = 0;
      while (i < data[0].rows.length) {
        let childRes = await query([
          {
            sql: "select * from app_novel where novel_id=?",
            values: [data[0].rows[i].novel_id],
          },
        ]);
        data[0].rows[i].pic =
          childRes[0].rows.length > 0
            ? "data:image/jpg;base64," +
              childRes[0].rows[0].pic.toString("base64")
            : ""; //blob转base64
        i++;
      }
      res.send({
        code: 200,
        msg: "成功",
        data: data[0].rows,
      });
    })
    .catch((err) => {
      next(err);
    });
}
//首页完本榜
export function app_getFinishrank(req, res, next) {
  query([
    {
      sql: "select * from app_finishrank",
      values: [],
    },
  ])
    .then(async (data) => {
      let i = 0;
      while (i < data[0].rows.length) {
        let childRes = await query([
          {
            sql: "select * from app_novel where novel_id=?",
            values: [data[0].rows[i].novel_id],
          },
        ]);
        data[0].rows[i].pic =
          childRes[0].rows.length > 0
            ? "data:image/jpg;base64," +
              childRes[0].rows[0].pic.toString("base64")
            : ""; //blob转base64
        i++;
      }
      res.send({
        code: 200,
        msg: "成功",
        data: data[0].rows,
      });
    })
    .catch((err) => {
      next(err);
    });
}
//首页口碑榜
export function app_getPraiserank(req, res, next) {
  query([
    {
      sql: "select * from app_praiserank",
      values: [],
    },
  ])
    .then(async (data) => {
      let i = 0;
      while (i < data[0].rows.length) {
        let childRes = await query([
          {
            sql: "select * from app_novel where novel_id=?",
            values: [data[0].rows[i].novel_id],
          },
        ]);
        data[0].rows[i].pic =
          childRes[0].rows.length > 0
            ? "data:image/jpg;base64," +
              childRes[0].rows[0].pic.toString("base64")
            : ""; //blob转base64
        i++;
      }
      res.send({
        code: 200,
        msg: "成功",
        data: data[0].rows,
      });
    })
    .catch((err) => {
      next(err);
    });
}
//首页高分榜
export function app_getTopscore(req, res, next) {
  query([
    {
      sql: "select * from app_topscore",
      values: [],
    },
  ])
    .then(async (data) => {
      let i = 0;
      while (i < data[0].rows.length) {
        let childRes = await query([
          {
            sql: "select * from app_novel where novel_id=?",
            values: [data[0].rows[i].novel_id],
          },
        ]);
        data[0].rows[i].pic =
          childRes[0].rows.length > 0
            ? "data:image/jpg;base64," +
              childRes[0].rows[0].pic.toString("base64")
            : ""; //blob转base64
        i++;
      }
      res.send({
        code: 200,
        msg: "成功",
        data: data[0].rows,
      });
    })
    .catch((err) => {
      next(err);
    });
}
//首页人气榜
export function app_getPopularityrank(req, res, next) {
  query([
    {
      sql: "select * from app_popularityrank",
      values: [],
    },
  ])
    .then(async (data) => {
      let i = 0;
      while (i < data[0].rows.length) {
        let childRes = await query([
          {
            sql: "select * from app_novel where novel_id=?",
            values: [data[0].rows[i].novel_id],
          },
        ]);
        data[0].rows[i].pic =
          childRes[0].rows.length > 0
            ? "data:image/jpg;base64," +
              childRes[0].rows[0].pic.toString("base64")
            : ""; //blob转base64
        i++;
      }
      res.send({
        code: 200,
        msg: "成功",
        data: data[0].rows,
      });
    })
    .catch((err) => {
      next(err);
    });
}
//查询小说,条件为可选
function selectNovel(req, res, next) {
  const schema = Joi.object().keys({
    user_id: Joi.string(),
    classify_id: Joi.string().strict(),
    book_name: Joi.string(),
    authorName: Joi.string(),
    pageSize: Joi.number().required(),
    pageNum: Joi.number().required(),
  });
  const result = Joi.validate(req.query, schema, { allowUnknown: true });
  if (result.error == null) {
    let sql = "select * from books where ";
    let values = [];
    let limit = ` limit ${
      (result.value.pageNum - 1) * result.value.pageSize
    } , ${result.value.pageSize}`;
    if (Object.keys(result.value).length > 0) {
      Object.keys(result.value).forEach((item) => {
        if (item == "pageSize" || item == "pageNum") {
        } else if (item == "book_name") {
          sql += `${item} like '%${result.value[item]}%' and `;
        } else {
          sql += `${item}=? and `;
          values.push(result.value[item]);
        }
      });
      sql = sql.substring(0, sql.length - 5) + limit + ";";
    } else {
      sql = "select * from books";
    }
    console.log(sql);
    query([
      {
        sql,
        values,
      },
    ])
      .then((out) => {
        console.log("日志位置在selectNovel.js文件:");
        console.log(limit);
        console.log(out);
        if (Array.isArray(out[0].rows)) {
          out[0].rows.map((item) => {
            item.book_describe = decoder.write(item.book_describe);
          });
          console.log("日志位置在selectNovel.js文件:");
          console.log("查到" + out[0].rows.length + "条");
          res.send({
            code: 200,
            msg: "查找成功",
            data: out[0].rows,
          });
        } else {
          res.send({
            code: 400,
            msg: "未找到相关书籍",
            data: [],
          });
        }
      })
      .catch((err) => {
        next(err);
      });
  } else {
    next(result.error);
  }
}
//查询小说详情
function selectNovelDetailInfo(req, res, next) {
  const schema = Joi.object().keys({
    book_id: Joi.string().required(),
  });
  const result = Joi.validate(req.query, schema, { allowUnknown: true });
  if (result.error == null) {
    query([
      {
        sql: `select count(*) from chapterlist where book_id=${req.query.book_id}`,
        values: [],
      },
      {
        sql: `select * from books where book_id=${req.query.book_id};`,
        values: [],
      },
    ])
      .then((out) => {
        console.log("日志位置在selectNovel.js文件:");
        console.log(out);
        let data = out[1].success ? out[1].rows[0] : {};
        data.book_describe = decoder.write(data.book_describe);
        data.book_create_time = SDTime.format(
          data.book_create_time,
          "YYYY-MM-DD HH:mm:ss"
        ); //创建时间
        let total = out[0].success ? out[0].rows[0]["count(*)"] : 0;
        res.send({
          code: 200,
          msg: "查询成功",
          total,
          data,
        });
      })
      .catch((err) => {
        next(err);
      });
  } else {
    next(result.error);
  }
}
//查询小说目录
function selectNovelChapterList(req, res, next) {
  const schema = Joi.object().keys({
    book_id: Joi.string().required(),
  });
  const result = Joi.validate(req.query, schema, { allowUnknown: true });
  if (result.error == null) {
    query([
      {
        sql: `select * from chapterlist where book_id=${req.query.book_id};`,
        values: [],
      },
    ])
      .then((out) => {
        console.log("日志位置在selectNovel.js文件:");
        console.log(out);
        if (out[0].rows.length > 0) {
          res.send({
            code: 200,
            msg: "查询成功",
            data: out[0].rows,
          });
        } else {
          res.send({
            code: 400,
            msg: "未查询到目录信息",
            data: [],
          });
        }
      })
      .catch((err) => {
        next(err);
      });
  } else {
    next(result.error);
  }
}
//查询小说章节内容
function selectChapterContent(req, res, next) {
  const schema = Joi.object().keys({
    chapter_id: Joi.string().required(),
  });
  const result = Joi.validate(req.query, schema, { allowUnknown: true });
  if (result.error == null) {
    query([
      {
        sql: "select * from chapters where chapter_id=?",
        values: [req.query.chapter_id],
      },
    ])
      .then((out) => {
        console.log("日志位置在selectNovel.js文件:");
        console.log(out);
        if (out[0].rows.length > 0) {
          out[0].rows[0].content = decoder.write(out[0].rows[0].content);
          out[0].rows[0].create_time = SDTime.format(
            out[0].rows[0].create_time,
            "YYYY-MM-DD HH:mm:ss"
          );
          out[0].rows[0].updateTime = SDTime.format(
            out[0].rows[0].updateTime,
            "YYYY-MM-DD HH:mm:ss"
          );
          res.send({
            code: 200,
            msg: "查询成功",
            data: out[0].rows[0],
          });
        } else {
          res.send({
            code: 400,
            msg: "未查到该章节内容",
            data: null,
          });
        }
      })
      .catch((err) => {
        next(err);
      });
  } else {
    next(result.error);
  }
}
//首页每种类型查四本小说
function selectFourNovel(req, res, next) {
  let arr = [10001, 10002, 10003, 10004, 10005, 10006, 10007, 10008, 10009];
  let arr2 = [];
  arr.forEach((item, index) => {
    arr2.push({
      sql: `select * from books where classify_id=${item} limit 0,4;`,
      values: [],
    });
  });
  query(arr2)
    .then((out) => {
      if (out.length > 0) {
        out.forEach((item, index) => {
          item.classify_id = arr[index];
          item.rows.forEach((k, p) => {
            k.book_describe = decoder.write(k.book_describe);
            k.create_time = SDTime.format(k.create_time, "YYYY-MM-DD HH:mm:ss");
            k.updateTime = SDTime.format(k.updateTime, "YYYY-MM-DD HH:mm:ss");
          });
        });
        res.send({
          code: 200,
          msg: "查询成功",
          data: out,
        });
      } else {
        res.send({
          code: 400,
          msg: "未查到该章节内容",
          data: null,
        });
      }
    })
    .catch((err) => {
      next(err);
    });
}
let pictureArr = [
  "https://img2.baidu.com/it/u=527075003,600981105&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500",
  "https://img2.baidu.com/it/u=2906128848,189930610&fm=253&fmt=auto&app=138&f=JPEG?w=529&h=500",
  "https://img2.baidu.com/it/u=390590988,2569407851&fm=253&fmt=auto&app=138&f=JPEG?w=501&h=500",
  "https://img1.baidu.com/it/u=804943137,859923978&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=644",
  "https://img1.baidu.com/it/u=2469814149,619061442&fm=253&fmt=auto?w=200&h=200",
];
///////txt文本小说专区
//查找返回图片数据
function findImageData(item) {
  return new Promise((resolve, reject) => {
    const __dirname =
      path.resolve() + `/public/novelTxt/${item.fileNameId}/hbh.jpg`;
    fs.readFile(__dirname, { encoding: "base64" }, (err, data) => {
      if (err) {
        // next(err);
        // console.log(err);
        item.txtPicture = "";
        resolve();
      } else {
        //txtPicture
        item.txtPicture = `data:image/jpg;base64,${data}`;
        resolve();
      }
    });
  });
}
//txt文本小说列表
function selectTxtNovel(req, res, next) {
  const schema = Joi.object().keys({
    limitSize: Joi.number().required(),
    ids: Joi.string().allow(""), //字符串用,号分割
  });
  const result = Joi.validate(req.body, schema, { allowUnknown: true });
  if (!result.error) {
    if (req.body.ids[req.body.ids.length - 1] == ",") {
      req.body.ids = req.body.ids.substring(0, req.body.ids.length - 1);
    }
    query([
      //这个SQL查询语句的意思是从名为"txtnovellist"的表中选取10条记录，按照id升序排序，而这10条记录的id必须大于等于一个随机生成的id值。
      {
        //${req.ids?'NOT IN ('+req.ids+')':''}
        sql: `SELECT * FROM txtnovellist WHERE classify_id=${
          req.body.classify_id
        } AND id ${
          req.body.ids ? "NOT IN (" + req.body.ids + ")" : ""
        } ORDER BY RAND() LIMIT ${req.body.limitSize};`,
        values: [],
      },
      {
        sql: `select count(*) from txtnovellist where classify_id=${req.body.classify_id}`,
        values: [],
      },
    ])
      .then(async (out) => {
        if (out[0].rows.length > 0) {
          //给每个文件读取图片
          let index = 0;
          while (index < out[0].rows.length) {
            await findImageData(out[0].rows[index]);
            index++;
          }
          res.send({
            code: 200,
            msg: "查询成功！",
            total: out[1].rows[0]["count(*)"],
            data: out[0].rows,
          });
        } else {
          res.send({
            code: 200,
            msg: "查询成功！",
            total: out[1].rows[0]["count(*)"],
            data: [],
          });
        }
      })
      .catch((err) => {
        next(err);
      });
  } else {
    next(result.error);
  }
}

//下载txt小说接口
function downTxtNovel(req, res, next) {
  let arr = Object.keys(req.body).map((item) => JSON.parse(item));
  const schema = Joi.object().keys({
    fileNameId: Joi.string().required(),
  });
  const result = Joi.validate(arr[0], schema, { allowUnknown: true });
  // return
  if (!result.error) {
    //查找这个目录
    if (!fs.existsSync("./public/novelTxt/" + arr[0].fileNameId)) {
      res.statusCode = 404;
      res.write("sorry,I am your god!");
    } else {
      let file = fs.readdirSync("./public/novelTxt/" + arr[0].fileNameId);
      let fileRes = file.find((element) => element.endsWith(".txt"));
      if (file.length > 0 && fileRes) {
        // 读取文件
        fs.readFile(
          `./public/novelTxt/${arr[0].fileNameId}/${fileRes}`,
          (err, data) => {
            if (err) {
              next(err);
            } else {
              // res.setHeader("Content-Type", "application/zip");
              var dis_str =
                "attachment; filename=" +
                encodeURI(fileRes, "GBK").toString("iso8859-1");
              res.setHeader("Content-Disposition", dis_str); //必须写这个，不然客户端无法下载正确，且文件会没有名字和后缀，这里就是告诉浏览器这是要下载什么
              res.end(data);
            }
          }
        );
      } else {
        res.statusCode = 404;
        res.write("sorry,I am your god!");
      }
    }
  } else {
    next(result.error);
  }
}
//获取当前图片的格式
function getImageType(str) {
  var reg = /\.(png|jpg|gif|jpeg|webp)$/;
  return str.match(reg)[1];
}
//保存图片
function saveImg() {
  const base64 = canvas.toDataURL().replace(/^data:image\/\w+;base64,/, ""); //必须去掉前缀
  const buffer = new Buffer(base64, "base64");
  fs.writeFile("保存路径", buffer, function (err) {
    if (err) throw err;
    console.log("保存成功");
  });
}
//获取小说种类
function getClassList(req, res, next) {
  query([
    {
      sql: "select * from classifys",
      values: [],
    },
  ])
    .then((out) => {
      res.send({
        code: 200,
        data: out[0].rows,
      });
    })
    .catch((err) => {
      next(err);
    });
}
export {
  selectNovel,
  selectNovelDetailInfo,
  selectNovelChapterList,
  selectChapterContent,
  selectFourNovel,
  selectTxtNovel,
  downTxtNovel,
  getClassList,
};
